import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tiktokadult/hj_model/video_model.dart';
import 'package:tiktokadult/hj_page/home_business/home_cell_style/video_simple_cell_widget.dart';
import 'package:tiktokadult/hj_page/home_business/home_cell_style/video_type_menu_view.dart';
import 'package:tiktokadult/hj_page/home_business/tag/video_tag_page.dart';
import 'package:tiktokadult/hj_utils/api_service/search_service.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/tools_base/debug_log.dart';
import 'package:tiktokadult/tools_base/loading/l_error_widget.dart';
import 'package:tiktokadult/tools_base/loading/loading_center_widget.dart';

import '../../../../hj_model/home/video_list_resp.dart';
import '../../../../tools_base/refresh/pull_refresh.dart';
import '../../../cartoon_business/search_tuji_cell.dart';
import '../../../community_business/widget/community_post_widget.dart';

enum SearchType {
  video("SP"), // 影片
  short("SHORT"), // 抖音
  post("COVER"), //帖子
  image("PIC"), // 色图
  novel("",kind: 3), // 小说,
  seed('SEED_LINK'), // 种子
  game('GAME'), //黄油
  user('USER'), // 用户
  comic("", kind: 2), //漫画
  cartoon("", kind: 1); //动漫


  final String realm;
  final int? kind; //ACG: 1、动漫 2、漫画 3、小说
  const SearchType(this.realm, {this.kind});
}

class SearchVideoResultPage extends StatefulWidget {
  final String keywords;
  final SearchType type;

  SearchVideoResultPage({
    super.key,
    required this.type,
    required this.keywords,
  });

  @override
  State<SearchVideoResultPage> createState() => _SearchVideoResultPageState();
}

class _SearchVideoResultPageState extends State<SearchVideoResultPage> {
  RefreshController refreshController = RefreshController();
  int pageNumber = 1;
  List<VideoModel>? videoList;
  List<VideoModel>? tagVidList;
  String? tagID;
  int sortIndex = 0;
  List<int> get sortNetValue => [3, 2, 1];
  int get sortParam => sortNetValue[sortIndex];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _loadData(sortParam);
    });
  }

  _loadData(int sortValue, {int page = 1, int size = 12}) async {
    try {
      VideoListResp? retResp = await SearchService.getMediaSearchData(widget.keywords,
          pageNumber: page, pageSize: size, realm: widget.type.realm, sortType: sortValue);
      pageNumber = page;
      videoList ??= [];
      videoList?.addAll(retResp?.videos ?? []);
      if (page == 1) {
        tagVidList = retResp?.tagVidList ?? [];
        tagID = retResp?.tagID;
      }
      if (retResp?.hasNext == false) {
        refreshController.loadNoData();
      } else {
        refreshController.loadComplete();
      }
    } catch (e) {
      refreshController.loadComplete();
      debugLog(e);
    }
    refreshController.refreshCompleted();
    videoList ??= [];
    if (mounted) setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    if (videoList == null && tagVidList == null) {
      return LoadingCenterWidget();
    } else if (videoList?.isEmpty == true && tagVidList?.isEmpty == true) {
      return CErrorWidget(
        retryOnTap: () {
          videoList = null;
          setState(() {});
          _loadData(sortParam);
        },
      );
    } else {
      return NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return [
            SliverToBoxAdapter(
              key: ValueKey(tagID),
              child: _buildTagWidget(),
            )
          ];
        },
        body: Column(
          children: [
            if (widget.type == SearchType.video || widget.type == SearchType.short)
              VideoTypeMenuView(
                ['最多收藏', "最新上架", "最多观看"],
                selectIndex: sortIndex,
                alignment: Alignment.center,
                callback: (value) {
                  sortIndex = value;
                  videoList = null;
                  _loadData(sortParam);
                  setState(() {});
                },
              ),
            Expanded(
              child: _buildContent(),
            ),
          ],
        ),
      );
    }
  }

  Widget _buildContent() {
    if (videoList == null) {
      return LoadingCenterWidget();
    } else if (videoList?.isEmpty == true) {
      return CErrorWidget(
        retryOnTap: () {
          videoList = null;
          setState(() {});
          _loadData(sortParam);
        },
      );
    } else {
      return pullYsRefresh(
        onInit: (ctr) => refreshController = ctr,
        onLoading: (ctr) => _loadData(sortParam, page: pageNumber + 1),
        onRefresh: (ctr) => _loadData(sortParam),
        child: _buildTypeList(),
      );
    }
  }

  Widget _buildTypeList() {
    if (widget.type == SearchType.video || widget.type == SearchType.short) {
      bool isShort = widget.type == SearchType.short;
      return GridView.builder(
        padding: EdgeInsets.only(left: 12, right: 12),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: isShort ? 3 : 2,
          mainAxisSpacing: 12,
          crossAxisSpacing: 6,
          childAspectRatio: isShort ? 111 / 190 : 168 / 154,
        ),
        itemCount: videoList?.length ?? 0,
        itemBuilder: (context, index) {
          return VideoSimpleCellWidget(
            videoModel: videoList![index],
            textLines: isShort ? 1 : 2,
          );
        },
      );
    } else if (widget.type == SearchType.image) {
      return GridView.builder(
        padding: EdgeInsets.only(left: 12, right: 12),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          mainAxisSpacing: 12,
          crossAxisSpacing: 6,
          childAspectRatio: 111 / 190,
        ),
        itemCount: videoList?.length ?? 0,
        itemBuilder: (context, index) {
          return SearchTujiCell(
            videoModel: videoList![index],
            textline: 1,
          );
        },
      );
    } else {
      return ListView.builder(
        padding: EdgeInsets.zero,
        itemCount: videoList?.length ?? 0,
        itemBuilder: (context, index) {
          return CommunityPostWidget(
            videoModel: videoList![index],
            videoModels: videoList,
          );
        },
      );
    }
  }

  Widget _buildTagWidget() {
    if (tagVidList?.isNotEmpty != true) return SizedBox();
    if (widget.type == SearchType.video || widget.type == SearchType.short) {
      bool isShort = widget.type == SearchType.short;
      return Container(
        padding: EdgeInsets.fromLTRB(12, 12, 12, 0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              "${widget.keywords} 标签内容",
              style: TextStyle(
                color: Color(0xE5FFFFFF),
                fontSize: 14,
              ),
            ),
            12.sizeBoxH,
            GridView.builder(
              itemCount: min(isShort ? 6 : 4, tagVidList?.length ?? 0),
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              padding: EdgeInsets.zero,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: isShort ? 3 : 2,
                mainAxisSpacing: 12,
                crossAxisSpacing: 6,
                childAspectRatio: isShort ? 111 / 190 : 168 / 154,
              ),
              itemBuilder: (context, index) {
                VideoModel videoModel = tagVidList![index];
                return VideoSimpleCellWidget(
                  videoModel: videoModel,
                  textLines: isShort ? 1 : 2,
                );
              },
            ),
            SizedBox(height: 12),
            GestureDetector(
              onTap: () {
                Get.to(VideoTagPage(TagsBean(id: tagID, name: widget.keywords)), preventDuplicates: false);
              },
              child: Container(
                height: 40,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: Color(0x1AFFFFFF),
                  borderRadius: BorderRadius.circular(3),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      "查看更多",
                      style: TextStyle(
                        color: Color(0xffEFEFEF),
                        fontSize: 14,
                      ),
                    ),
                    SizedBox(width: 6),
                    Icon(
                      Icons.keyboard_arrow_right,
                      color: Color(0xffDCDCDC),
                      size: 18,
                    ),
                  ],
                ),
              ),
            ),
            SizedBox(height: 6),
          ],
        ),
      );
    }
    return SizedBox();
  }
}
